package me.mritd.quartz.job;


import me.mritd.email.MailSender;
import me.mritd.vo.EmailVo;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
 * 
 * @ClassName SendEmailJob 
 * @Description TODO 邮件发送JOb类
 * @author 漠然  mritd@mritd.me
 * @date 2015年10月6日 下午5:31:26 
 * @version 1.0
 */
public class SendEmailJob implements Job{
	
	private static final Logger logger = Logger.getLogger(SendEmailJob.class);
	
	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		
		//邮件发送状态	真正调用SMTP的状态
		boolean sendHtmlMail = false;
		
		//全操作Catch  任意异常则判定 发送失败 任务终止
		try {
			
			JobDataMap dataMap = context.getJobDetail().getJobDataMap();
			EmailVo mailInfo = (EmailVo) dataMap.get("mailInfo");
			
			if (mailInfo==null) {
				logger.error("XXXXXX mailInfo为空,发送任务终止!");
				throw new JobExecutionException("mailInfo为空,发送任务终止!");
			}
			
			//准备分批次发送
			String allAddr = mailInfo.getToAddress();
			String allAddrArray[] = allAddr.split(",");
		
			if (allAddrArray.length>20) {	//超过20人则分批发送
				//缓存Email地址
				StringBuffer tempAddr = new StringBuffer();	
				//发送批次
				int level = 1;	
				//遍历所有Email地址
				for (int i = 0; i < allAddrArray.length; i++){
					tempAddr.append(allAddrArray[i]);
					tempAddr.append(",");
					if (i!=0&&i%20==0) {
						logger.info("###### 第["+level+"]批邮件发送地址:"+tempAddr);
						mailInfo.setToAddress(tempAddr.toString());
						sendHtmlMail = new MailSender().sendHtmlMail(mailInfo);
						logger.info("###### 准备线程休眠，防止被 kill......");
						Thread.sleep(40000);
						if (!sendHtmlMail) {
							logger.error("XXXXXX 循环发送失败!终止发送!");
							break;
						}
						tempAddr.setLength(0); 	//清空缓存邮件地址
						level++;
					}else if (i==allAddrArray.length-1) {	//最后一批
						logger.info("###### 最后一批邮件发送地址:"+tempAddr);
						mailInfo.setToAddress(tempAddr.toString());
						sendHtmlMail = new MailSender().sendHtmlMail(mailInfo);
						if (!sendHtmlMail) {
							logger.error("XXXXXX 最后一批发送失败!终止发送!");
							break;
						}
					}
				}
				//所有发送完成后恢复邮件地址
				mailInfo.setToAddress(allAddr);
				
			}else {
				mailInfo.setToAddress(allAddr);
				sendHtmlMail = new MailSender().sendHtmlMail(mailInfo);
				if (sendHtmlMail) logger.info("###### 单次邮件发送成功!");
			}
			
			//任意一次失败 则判定此次任务失败! 根据日志查找发送到哪一批 手动重新发送
			if (!sendHtmlMail) {
				throw new JobExecutionException("邮件发送失败!");
			}		
		} catch (Exception e) {
			logger.info("###### 邮件发送出现异常:",e);
			throw new JobExecutionException("邮件发送失败!");
		}
	}

}
